/*Hita0WssSbjpM+C19QDJ008vFiFXoRYM5fFc3Y8SmebGdTMFwKIbklXKmPe+JYpy*/
/**
 * 卡片 card_head 区域按钮的事件处理
 */
import {ajax, base, toast, print, output, cardCache} from 'nc-lightapp-front';

import {isFunction} from '../../../../public/util/tools';

import constants from '../../constants';
import {getPkTransitype, getAreaItemFields} from '../../utils';
import pageInfoClick from './pageInfoClick';
import setStatus from './setStatus';
import initTemplate from './initTemplate';
import ampub from 'ampub';
import fa from 'fa';
// import ampub from '../../../../../ampub/common/collection/release';
// import fa from '../../../../common/collection/release';

const {components, utils} = ampub;
const {fa_components, fa_utils} = fa;

const {openEquipCardByPk} = components.queryAboutUtils;
const {getMultiLangByID} = utils.multiLangUtils;
const {getContext, loginContextKeys} = components.LoginContext;
const {showConfirm, MsgConst, showMessage, showErrorMessageByRes} = utils.msgUtils;
const {queryAboutVoucher, openToVouchar} = components.queryVocherUtils;


const {cardFaImageView, cardFaImageScan} = fa_components.ImageMng;
const {CardLinkToBill} = fa_components.CardLinkToBillUtil;
const {metaUtil} = fa_utils;

import afterEvent from './afterEvent';
import {updateAssetGroupItem, updateDeptmethodItem} from "./utils";


const basicInfoForm = constants.AREA.CARD.BASIC_INFO_AREA;
const financeForm = constants.AREA.CARD.FINANCE_AREA;
const usedept_tab = constants.AREA.CARD.USEDEPT_TAB;
const subequip_tab = constants.AREA.CARD.SUBEQUIP_TAB;
const assetAllArea = constants.AREA.CARD.ASSET_ALL;
const {BILL_SOURCE_TYPES, ASSET_ADDED_WAY} = constants;
const {FIELDS, assetDataSource} = constants;

const {
    ADD,
    EDIT,
    DELETE,
    SAVE,
    SaveAdd,
    CANCEL,
    REFRESH,
    COPY,
    SimulateDep,
    SimulateAccudep,
    PRINT_CHILD,
    PRINT_NOCHILD,
    Output,
    QueryAboutCard,
    QueryAboutVoucher,
    FABillQueryAboutVoucher,
    QueryAboutBusiness,
    Attachment,
    FAReceiptShow,
    FAReceiptScan,
} = constants.CARD_BTNS.HEAD;

export default function (props, id) {
    const that = this;
    switch (id) {
        //修改按钮
        case EDIT:
            doEdit(that);
            break;

        case DELETE:
            showConfirm.call(this, props, {
                type: MsgConst.Type.Delete,
                beSureBtnClick: () => {
                    doDelete(that);
                }
            });
            break;

        case SAVE:
            doSave(that);
            break;

        case SaveAdd:
            doSaveAdd(that);
            break;

        case COPY:
            doCopy(that);
            break;

        case PRINT_CHILD:
            doPrintChild(that);
            break;

        case PRINT_NOCHILD:
            doPrintNoChild(that);
            break;

        case Output:
            doOutput(that);
            break;

        case CANCEL:
            showConfirm.call(this, props, {
                type: MsgConst.Type.Cancel,
                beSureBtnClick: () => {
                    doCancel(that);
                }
            });

            break;

        case REFRESH:
            doRefresh(that);
            break;

        //模拟折旧
        case SimulateDep:
            doSimulateDep(that);
            break;

        //模拟累计折旧
        case SimulateAccudep:
            doSimulateAccudep(that);
            break;

        //联查设备卡片
        case QueryAboutCard:
            queryAboutCard(that.props);
            break;

        //附件
        case Attachment:
            attachment(that.props);
            break;

        // 影像扫描
        case FAReceiptScan:
            faReceiptScan.call(this, props);
            break;

        // 影像查看
        case FAReceiptShow:
            faReceiptShow.call(this, props);
            break;

        //来源单据
        case QueryAboutBusiness:
            billreview.call(that);
            break;

        //联查凭证
        case QueryAboutVoucher:
            // tableId为区域编码，第三个参数为主键编码，appcode为应用编码,新增参数，标志列表态联查
            let appcode = this.props.pageConfig.appid;
            queryAboutVoucher(props, basicInfoForm, 'pk_card', appcode);
            break;

        //联查业务凭证
        case FABillQueryAboutVoucher:
            faBillQueryAboutVoucher(that);
            break;

        //卡片交易类型按钮点击
        default:
            doAdd(that, id);
            break;

    }
}

//新增-点击新增下的交易类型按钮
function doAdd(that, id) {
    that.resetOnAdd();
    that.props.setUrlParam({
        transiType: id,
        pagecode: id,
        status: constants.UISTATE.ADD,
        id: '',//id（pk）置空
    });
    //交易类型改变，需要刷新当前页
    initTemplate.call(that, that.props).then(() => {
        that.financeOrgInit();
        setStatus.call(that, that.props);
    });

}

//保存前
function saveBefore() {
    //校验是否存在账簿数据
    let valid = (this.state.accbooks && this.state.accbooks.length);
    if (!valid) {
        /*国际化处理：没有可用的资产账簿*/
        showMessage(null, {content: getMultiLangByID('201201504A-000003'), color: 'warning'});
        return valid;
    }
    return checkNull.call(this);
}

//前端进行非空校验
function checkNull() {
    //表头必输项校验
    let checkResult = this.props.form.isCheckNow([basicInfoForm, financeForm]);
    if (!checkResult) {
        return false;
    }

    let valid = true;
    //如果多账簿的情况下，用户不切换到报告账簿的情况下，将无法验证报告账簿的非空值，这里手动验证
    let fieldsRequired = metaUtil.getRequiredFieldByArea(this.props, financeForm);
    let accbooks = this.state.accbooks;
    if (accbooks && accbooks.length > 1) {
        for (let i = 1; i < accbooks.length; i++) {
            let {pk_accbook, accbookName} = accbooks[i];
            let assetvo = this.assetDataMap[pk_accbook];
            let emptyFields = new Set();
            fieldsRequired.map((field) => {
                if (!assetvo.values[field].value) {
                    valid = false;
                    emptyFields.add(field);
                }
            });
            if (!valid) {
                // show error msg
                let emptyFieldsLabel = metaUtil.getFieldLabels(this.props, financeForm, emptyFields);
                let title = "[" + accbookName + "] " + getMultiLangByID('facommon-000015');
                emptyFieldsLabel = emptyFieldsLabel.map(f => '[' + f + ']');
                showMessage(this.props, {
                    content: '<div>' + title + '</div>' + '<div>' + emptyFieldsLabel.join(', ') + '</div>',
                    color: 'danger'
                });

                break;
            }
        }
    }

    if (!valid) {
        return false;
    }

    //过滤空行
    let props = this.props;
    props.cardTable.filterEmptyRows(usedept_tab, ['pk_dept', 'usescale'], 'include');
    props.cardTable.filterEmptyRows(subequip_tab, []);//这里第二个参数需要一个空数组

    //校验多使用部门页签
    let usedep_flag = props.form.getFormItemsValue(basicInfoForm, 'usedep_flag').value;
    if (usedep_flag) {
        // 表体必输校验
        let allRows = props.cardTable.getVisibleRows(usedept_tab);
        if (!allRows || allRows.length < 2) {
            showMessage(props, {content: getMultiLangByID('201201504A-000010'), color: 'warning'});
            return false;
        }
        checkResult = props.cardTable.checkTableRequired(usedept_tab);
        if (!checkResult) {
            return false;
        } else {
            //不允许重复
            let deptSet = new Set();
            let deptScaleSet = new Set();
            allRows.map((row) => {
                deptSet.add(row.values.pk_dept.value);
                deptScaleSet.add(row.values.usescale.value);
            });
            if (deptSet.size !== allRows.length) {
                showMessage(props, {content: getMultiLangByID('201201504A-000011'), color: 'danger'});
                return false;
            }
            let hasNegative = [...deptScaleSet].some((n) => {
                return n < 0;
            });
            if (hasNegative) {
                showMessage(props, {content: getMultiLangByID('201201504A-000012'), color: 'danger'});
                return false;
            }
        }
        return true;
    }
    return true;
}


function doSaveAdd(that) {
    doSave(that, true);
}

//保存单据
function doSave(that, isSaveAdd = false) {
    if (!saveBefore.call(that)) {
        return;
    }
    //组装用于提交到后台的数据
    that.syncDataForCommit();

    let url = constants.URL.SAVE; //新增保存
    if (that.props.getUrlParam('status') === constants.UISTATE.EDIT) {
        url = constants.URL.UPDATE; //修改保存
    }

    //保存需要的辅助参数
    let paramMap = that.getAssitParam();
    const pk_card = that.basicInfoData.values['pk_card'].value;
    let isCategoryChanged = pk_card ? paramMap[pk_card]['editCategoryWhenUpdate'] : false;

    //获取多使用部门数据
    let usedeptData = getCardtableData.call(that, usedept_tab);
    //后台是先删除之前的然后再重新插入
    usedeptData = filterDeletedRows(usedeptData);

    //获取 附属设备数据
    let subequipData = getCardtableData.call(that, subequip_tab);

    let assetvos = Object.values(that.assetDataMap);


    //清除模拟折旧数据
    // 如果卡片新增模拟折旧或者是该账簿可以修改，那么清空当月计提的数据
    const status = that.props.getUrlParam('status');
    for (let assetvo of assetvos) {
        const pk_accbook = assetvo.values.pk_accbook.value;
        if (status === constants.UISTATE.ADD || !that.editAbleBook || that.editAbleBook.includes(pk_accbook)) {
            assetvo.values.deprate = {value: 0, display: 0};
            assetvo.values.depamount = {value: 0, display: 0};
        }

        //编辑态 && editCategoryWhenUpdate=false, 回写历史表主键（在建卡日期多次改变中丢失）
        if(status === constants.UISTATE.EDIT && !isCategoryChanged) {
            assetvo.values.pk_cardhistory = that.assetDataMapBack[assetvo.values.pk_accbook.value].values.pk_cardhistory;
        }
    }

    //判断是否是类别变化
    if (that.props.getUrlParam('status') === constants.UISTATE.EDIT) {
        const pk_card = that.basicInfoData.values['pk_card'].value;
        if (paramMap[pk_card]['editCategoryWhenUpdate']) {
            for (let assetvo of assetvos) {
                assetvo.status = constants.DATA_STATUS.NEW;
            }
        }
    }

    //预算控制
    if(that.budgetStrategy) {
        Object.assign(paramMap[pk_card], that.budgetStrategy);
    }

    //组装提交数据：按照一主多子的格式
    let data = {
        pageid: that.state.pageCode,
        templateid: that.templateid,
        userjson: paramMap,
        heads: [{
            pageid: that.state.pageCode,
            model: {
                areacode: assetAllArea,
                areaType: 'table',
                rows: assetvos,
            }
        }],
        bodysMap: {
            [usedept_tab]: {
                pageid: that.state.pageCode,
                model: {
                    areacode: usedept_tab,
                    rows: usedeptData,
                    areaType: 'table',
                }
            },
            [subequip_tab]: {
                pageid: that.state.pageCode,
                model: {
                    areacode: subequip_tab,
                    rows: subequipData,
                    areaType: 'table',
                }
            }
        },
    };

    //保存前执行验证公式:只支持【基本信息】区域的验证
    that.props.validateToSave({
            pageid: that.state.pageCode,
            model: {
                areacode: basicInfoForm,
                rows: assetvos,
            }
        }, () => {
            ajax({
                url,
                data,
                success: (res) => {
                    let {success, data} = res;
                    if(success && data) {
                        let BudgetMessage = data.BudgetMessage;//预算控制消息

                        if (BudgetMessage) {
                            that.props.modal.show(constants.MODAL_ID.ConfirmModal, {
                                title: getMultiLangByID('201201504A-000053')/* 国际化：'提示'*/,
                                content:  BudgetMessage,
                                beSureBtnClick: () => {
                                    that.budgetStrategy = {'SkipCodes': 'Y'};
                                    doSave(that, isSaveAdd);
                                }
                            });
                        } else {
                            showMessage(that.props, {type: MsgConst.Type.SaveSuccess});
                            saveAfter(that, data, isSaveAdd, isCategoryChanged);
                        }
                    }

                },
                error: (err) => {
                    showErrorMessageByRes(that.props, err);
                }
            })
        },
        null,
        'form'
    );
}

function saveAfter(that, data, isSaveAdd = false, isCategoryChanged = false) {
    //1、更新缓存数据
    const status = that.props.getUrlParam('status');
    if (status === constants.UISTATE.EDIT) {//编辑 -> 保存成功
        // 解锁卡片
        lockcards.call(that, 'unlock');
        if (isCategoryChanged) {//是修改了资产类别，先删除缓存再新增缓存
            let assetvos_bak = Object.values(that.assetDataMapBack);
            let pk_cardhistorys_bak = assetvos_bak.map((assetvo) => assetvo.values.pk_cardhistory.value);
            let pk_card = that.getHeadAttributeValue(data, 'pk_card');
            let delData = {pk_card, pk_cardhistorys: pk_cardhistorys_bak};
            that.updateAssetCache(delData, 'del');

            that.updateAssetCache(data, 'add');
        } else {//直接更新缓存
            that.updateAssetCache(data, 'update');
        }
    } else {//新增保存成功
        //更新缓存
        that.updateAssetCache(data, 'add');
    }

    if (isSaveAdd) {//【保存新增】按钮
        that.props.setUrlParam({id: ''});
        that.resetOnAdd();
        setStatus.call(that, that.props, constants.UISTATE.ADD);

        //展开表体
        that.props.cardTable.toggleCardTable([subequip_tab, usedept_tab], true);

        let assetAll = data.heads[0] && data.heads[0].assetAll && data.heads[0].assetAll.rows[0];
        const pk_org_v = assetAll.values['pk_org_v'];
        const pk_org = assetAll.values['pk_org'];
        that.props.form.setFormItemsValue(basicInfoForm, {
            pk_org_v,
            pk_org
        });

        afterEvent.call(that, that.props, basicInfoForm, 'pk_org', pk_org);
    } else {
        const pk_cardhistory = that.getHeadAttributeValue(data, 'pk_cardhistory');
        that.props.setUrlParam({
            status: constants.UISTATE.BROWSE,
            id: pk_cardhistory
        });
        //2、更新界面数据
        that.setValue(data);
        setStatus.call(that, that.props);
    }
}


function doCopy(that) {
    let pk_card = that.getPkcardFromUrl();
    that.facardCopy.showCopyCardDialog(that, pk_card);
    that.facardCopy.setCopySuccessAfter((pk) => {
        //加载复制成功的最后一条数据
        pageInfoClick.call(that, that.props, pk);

        // 设置翻页控件当前id
        that.props.cardPagination.setCardPaginationId({ id: pk });
    });
}

/**
 * 修改按钮
 *
 * //更新的时候需要获取的数据
 *       this.depmethodFormulaFieldMap = {}; //折旧方法公式字段
 *       this.depmethods = [];//折旧方法列表
 *       this.fa10param = {};//FA10 参数<pk_accbook, boolean>
 *       this.accbookCurrency = {};//账簿币种
 *       this.is_allow_dept_midlev = false;
 *
 * @param that
 * @returns {Promise<any>}
 */
function doEdit(that) {
    //编辑之前
    that.editAbleBook = [];
    that.editCategoryWhenUpdate = false;
    that.budgetStrategy = null;

    //日期类型字段恢复可编辑
    that.props.form.setFormItemsDisabled(basicInfoForm, {
        'business_date': false,
        'begin_date': false,
        'close_date': false,
    });
    if (that.state.financeShowFlag) {
        that.props.form.setFormItemsDisabled(financeForm, {
            'dep_start_date': false,
            'dep_end_date': false,
        });
    }

    //编辑校验
    let isValidate = true;
    let errorMsg = '';

    //获取当前账簿的数据, 没有选中的账簿时直接返回
    const currentPkaccbook = that.state.currentPkaccbook;
    const assetvo = that.getAccbookDataByPkaccbook(currentPkaccbook);
    const pk_card = assetvo.values.pk_card.value;

    const promise = new Promise(function (resolve, reject) {
        if (pk_card) {
            ajax({
                url: constants.URL.EDIT,
                data: {
                    pk: pk_card,
                    resourceCode: '2012016030', //固定资产卡片维护和原始卡片走同一个资源号
                },
                success: (res) => {
                    let {success, data} = res;
                    if (success) {
                        isValidate = data['validate'];
                        let failure = data['failure'];

                        if (failure) {
                            errorMsg = failure;
                            reject(failure);
                            return;
                        }
                        if (!isValidate) {
                            reject(isValidate);
                            return;
                        }

                        that.editAbleBook = data['editAbleBook'];
                        that.setFAParam(data['paramVO']);
                        resolve(data);
                    }
                },
                error: (err) => {
                    reject(err);
                }
            });
        } else {
            resolve();
        }
    }).then((resData) => {
            //卡片校验通过，可以编辑
            //对卡片进行加锁
            lockcards.call(that, 'lock').then(() => {
                setStatus.call(that, that.props, constants.UISTATE.EDIT);
            }, () => {
                setStatus.call(that, that.props, constants.UISTATE.BROWSE);
            }).then(() => {
                
                //修改时 将卡片数据更新为月初数据
                let monthBeginvos = resData['monthBeginvos'];
                let MonthBeginFieldsWhenEdit = resData['MonthBeginFieldsWhenEdit'];

                if(monthBeginvos) {
                    monthBeginvos.map((beginVO)=>{
                        let accbook = beginVO.pk_accbook;
                        let assetVO = that.assetDataMap[accbook];
                        MonthBeginFieldsWhenEdit.map((field)=>{
                            assetVO.values[field].value = beginVO[field];
                        });
                    });

                    //更新界面数据
                    const pkaccbook = that.state.currentPkaccbook;
                    const accbookData4Form = that.getAccbookDataByPkaccbook4Form(pkaccbook);
                    const basicInfoData4Form = that.getBasicInfoData4Form();
                    if (that.state.financeShowFlag) {
                        that.props.form.setAllFormValue({
                            [basicInfoForm]: basicInfoData4Form,
                            [financeForm]: accbookData4Form
                        });
                    } else {
                        that.props.form.setAllFormValue({
                            [basicInfoForm]: basicInfoData4Form
                        });
                    }
                }


                //判断使用部门、附属设备页签是否可以编辑
                let isAllowed = true;
                if (!that.editAbleBook || !that.editAbleBook.length) {
                    isAllowed = false;
                } else {
                    //editAbleBook 中必须包括所有的账簿 才允许修改
                    isAllowed = !that.state.accbooks.some((book) =>
                        !that.editAbleBook.includes(book.pk_accbook)
                    );
                }

                //当前是单使用部门 或者 存在后续业务操作，不允许编辑使用部门页签
                const usedep_flag = that.props.form.getFormItemsValue(basicInfoForm, 'usedep_flag').value;
                if (!usedep_flag || !isAllowed) {
                    // 设置表体页签不能编辑
                    // 多使用部门页签上的按钮不可以使用
                    let btns = Object.values(constants.CARD_BTNS.TABLE_HEAD.USEDEPT_TAB);
                    that.props.button.setButtonVisible(btns, false);
                    that.props.cardTable.setStatus(usedept_tab, constants.UISTATE.BROWSE);
                }
                if (!isAllowed) {
                    //设置附属设备页签
                    let btns = Object.values(constants.CARD_BTNS.TABLE_HEAD.SUBEQUIP_TAB);
                    that.props.button.setButtonVisible(btns, false);
                    that.props.cardTable.setStatus(subequip_tab, constants.UISTATE.BROWSE);
                }

                //更新工作量字段的编辑性
                const accbookData = that.getAccbookDataByPkaccbook4Form(that.state.currentPkaccbook);
                updateDeptmethodItem.call(that, that.props, accbookData);

                //更新【资产组】参照
                updateAssetGroupItem(that.props, !that.isHeadAssetFinanceorg);
            });

        },
        (err) => {
            showMessage(that.props, {content: errorMsg || err.message || getMultiLangByID('201201504A-000013'), color: 'danger'});
            setStatus.call(that, that.props, constants.UISTATE.BROWSE);
        });

    return promise;
}


//删除单据
function doDelete(that) {
    if (doDeleteBeforeCheck(that)) {
        return;
    }

    let pk_cardhistorys = [];
    for (let pk_accbook in that.assetDataMap) {
        let assetvo = that.assetDataMap[pk_accbook];
        pk_cardhistorys.push(assetvo.values.pk_cardhistory.value);
    }

    const pk = that.getPkcardFromUrl();
    if (pk) {
        const ts = that.props.form.getFormItemsValue(basicInfoForm, 'ts').value;
        const data = {
            pks: pk,
            tss: ts,
        };
        ajax({
            url: constants.URL.DELETE,
            data,
            success: (res) => {
                let {success, data} = res;
                if (success) {
                    let {allSuccess, message, suceessArr, failure} = data;
                    if (failure) {
                        showMessage(that.props, {content: failure, color: 'danger'});
                    } else if (allSuccess) {
                        /*国际化处理：删除成功*/
                        showMessage(that.props, {type: MsgConst.Type.DeleteSuccess});
                        let delData = {pk_card: pk, pk_cardhistorys};
                        deleteAfter.call(that, delData);
                    } else {
                        if (message && message.length === 1) {
                            toast({content: message[0], color: 'danger'});
                        } else {
                            toast({
                                duration: 'infinity',
                                color: 'danger',
                                content: message.shift(),
                                groupOperation: true,
                                groupOperationMsg: message,
                                TextArr: [getMultiLangByID('amcommon-000005'),
                                    getMultiLangByID('amcommon-000006'),
                                    getMultiLangByID('amcommon-000007')] /* 国际化处理： ['展开', '收起', '关闭'] */
                            });
                        }
                    }
                } else {
                    /*国际化处理：删除失败*/
                    showMessage(that.props, {type: MsgConst.Type.DeleteFailed});
                }
            },
            error: (err) => {
                showErrorMessageByRes(that.props, err);
            }
        });
    }
}


//删除单据前检查
function doDeleteBeforeCheck(that) {
    const source = that.props.form.getFormItemsValue(basicInfoForm, 'bill_source').value;
    let error = '';
    if (source === BILL_SOURCE_TYPES.conbin_src) {
        //合并生成卡片,不能删除
        error = getMultiLangByID('201201504A-000014') /* 国际化处理： 合并生成卡片,不能删除*/;

    } else if (source === BILL_SOURCE_TYPES.split_src) {
        // 拆分卡片,不能删除
        error = getMultiLangByID('201201504A-000015') /* 国际化处理： 拆分卡片,不能删除*/;
    } else if (source === BILL_SOURCE_TYPES.deploy_in_src) {
        // 调拨增加资产，不能删除
        error = getMultiLangByID('201201504A-000016') /* 国际化处理： 调拨增加资产,不能删除*/;
    } else {
        const newasset_flag = that.props.pageConfig.newasset_flag;
        if (newasset_flag > ASSET_ADDED_WAY.isNew) {
            //非当月增加，不能删除
            error = getMultiLangByID('201201504A-000017') /* 国际化处理： 非当月增加，不能删除*/;
        }
    }

    if (error) {
        showMessage(that.props, {content: error, color: 'danger'});
    }

    return error;

}

//删除成功后
function deleteAfter(delData) {
    //删除成功
    //根据当前id,获取下个id
    let id = this.props.getUrlParam("id");
    let nextId = getNextId.call(this, id);

    //调用删除缓存数据方法（需要同时删除 allpks 和 列表态表格中的数据）
    this.updateAssetCache(delData, 'del');

    //加载下一条数据
    pageInfoClick.call(this, this.props, nextId);

}

//获取下一个卡片的ID, （仅供删除卡片后获取下一个 pk_card 使用）
function getNextId(currId) {
    //根据当前id,获取下个id
    let nextId = cardCache.getNextId(currId, assetDataSource);
    this.props.setUrlParam({id: nextId});
    if (nextId) {
        let pk_card_next = this.getPkcardFromUrl();

        if (pk_card_next != this.curr_pk_card) {
            return nextId;
        } else {
            //多账簿情况下：新增一个卡片->删除卡片后，getNextId 会出现递归死循环（具体见平台 cardCache.getNextId）
            cardCache.deleteCacheById('pk_cardhistory', currId, assetDataSource);
            return getNextId.call(this, nextId);
        }
    }
    return null;
}


function doCancel(that) {
    const status = that.props.getUrlParam('status');
    if (status === constants.UISTATE.ADD) {//新增 --> 取消
        // 加载编辑前数据，如果编辑前没有数据，则加载当前列表最后一条数据，如果还没有，显示为空不处理
        let id = cardCache.getCurrentId(assetDataSource);
        if (!id) {
            id = cardCache.getCurrentLastId(assetDataSource);
        }
        // 设置翻页控件当前id
        that.props.cardPagination.setCardPaginationId({ id });
        pageInfoClick.call(that, that.props, id);

    } else {//修改 --> 取消
        // 解锁卡片
        lockcards.call(that, 'unlock');

        that.props.setUrlParam({status: constants.UISTATE.BROWSE});
        that.props.form.cancel(basicInfoForm);
        that.props.form.cancel(financeForm);

        //数据恢复到编辑前
        const {assetDataMapBack} = that;
        that.assetDataMap = JSON.parse(JSON.stringify(assetDataMapBack)); //解决对象引用修改了 assetDataMapBack 的值

        const assetvos = Object.values(that.assetDataMap);
        that.parseAssetData({rows: assetvos});

        //恢复页签数据
        [usedept_tab, subequip_tab].forEach((tab) => {
            that.props.cardTable.resetTableData(tab);
        });

        //收起表体页签
        that.props.cardTable.toggleCardTable(constants.TabsHideDefault, false);

        setStatus.call(that, that.props, constants.UISTATE.BROWSE);
    }
}

//刷新界面
function doRefresh(that) {
    let pk_card = that.getPkcardFromUrl();

    that.clearBodies();

    new Promise(function (resolve, reject) {
        resolve(that.getData(pk_card));
    }).then(
        (data) => {
            if (data) {
                /*国际化处理：刷新成功*/
                showMessage(that.props, {type: MsgConst.Type.RefreshSuccess});
                that.getDataBack(data);
            }
        },
        () => {
            // 未查询到数据，清除界面
            setStatus.call(that, that.props, constants.UISTATE.BLANK);
        }
    );
}

function doPrintChild(that) {
    let nodekey = '201201504A_child';
    doPrint(that, nodekey);
}

function doPrintNoChild(that) {
    let nodekey = '201201504A_nochild';
    doPrint(that, nodekey);
}

function doPrint(that, nodekey) {
    let printData = getPrintData.call(that, that.props, 'print');
    printData.nodekey = nodekey || printData.nodekey;
    if (!printData) {
        /*国际化处理：请选择需要打印的数据*/
        showMessage(that.props, {type: MsgConst.Type.ChoosePrint});
        return;
    }
    print(
        'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
        constants.URL.PRINT_CARD, // 后台打印服务url
        printData
    );
}

function doOutput(that) {
    let printData = getPrintData.call(that, that.props, 'output');
    //输出默认为不带副卡的模板
    printData.nodekey = '201201504A_nochild';
    if (!printData) {
        /*国际化处理：请选择需要输出的数据*/
        showMessage(that.props, {type: MsgConst.Type.ChooseOutput});
        return;
    }

    output({
        url: constants.URL.PRINT_CARD,
        data: printData
    });
}

/*
 * 获取打印数据
 */
function getPrintData(props, outputType = 'print') {
    const {pageConfig} = this.props;
    let printNodekey = null;

    let pk_card = this.curr_pk_card;
    if (!pk_card) {
        return;
    }

    let period = this.basicInfoData.values['period'].value;
    let accyear = this.basicInfoData.values['accyear'].value;
    let pk_cardhistory = this.basicInfoData.values['pk_cardhistory'].value;
    let pk_accbook = this.state.currentPkaccbook;
    let obj = {
        pk_cardhistory,
        pk_card,
        period,
        accyear,
        pk_accbook
    };

    let pks = [JSON.stringify(obj)];
    let printData = {
        filename: pageConfig.title, // 文件名称
        nodekey: printNodekey, // 模板节点标识
        oids: pks, // 需要打印数据主键
        outputType // 输出类型
    };
    return printData;
}

function linkToList(props, param = {}) {
    let defaultParam = {
        pagecode: constants.PAGE_CODE.LIST
    };
    props.pushTo('/list', Object.assign(defaultParam, param));
}

//获取 cardTable 的数据
function getCardtableData(areacode) {
    //过滤空行
    this.props.cardTable.filterEmptyRows(areacode);
    return this.props.cardTable.getAllRows(areacode);
}

//过滤掉已删除的数据
function filterDeletedRows(rows) {
    let newrows = rows;
    if(rows && rows.length) {
        newrows =  rows.filter( (r) => r.status != constants.DATA_STATUS.DELETED )
    }
    return newrows;
}

//模拟折旧
function doSimulateDep(that) {
    if (!doSimulateBefore(that)) {
        return;
    }

    doCurrentAccbookEdit(that, constants.URL.simulateDep, () => {
        /*国际化处理：模拟折旧成功*/
        showMessage(that.props, {content: getMultiLangByID('201201504A-000018'), color: 'success'});

    });
}

//模拟累计折旧
function doSimulateAccudep(that) {
    if (!doSimulateBefore(that)) {
        return;
    }

    doCurrentAccbookEdit(that, constants.URL.simulateAccuDep, () => {
        /*国际化处理：模拟累计折旧成功*/
        showMessage(that.props, {content: getMultiLangByID('201201504A-000019'), color: 'success'});
    });
}

//模拟折旧、模拟累计折旧前校验
function doSimulateBefore(that) {
    //1、非空校验
    if (!checkNull.call(that)) {
        return false;
    }
    //组装用于提交到后台的数据
    that.syncDataForCommit();
    return true;
}

//当前账簿的编辑
function doCurrentAccbookEdit(that, url, successBack, errorBack) {
    //获取当前账簿的数据, 没有选中的账簿时直接返回
    if (!that.state.currentPkaccbook) {
        return;
    }
    const currentPkaccbook = that.state.currentPkaccbook;
    const assetvo = that.getAccbookDataByPkaccbook(currentPkaccbook);

    const pageCode = that.state.pageCode;
    let data = {
        grid: {
            pageid: pageCode,
            templetid: that.templateid,
            model: {
                areacode: assetAllArea,
                areaType: 'table',
                rows: [assetvo]
            },
        }
    };

    ajax({
        url,
        data,
        success: (res) => {
            let {success, data} = res;
            if (success && data && data.heads) {

                let assetAllData = [];
                data.heads.forEach((head) => {
                    if (head.assetAll && head.assetAll.rows && head.assetAll.rows.length > 0) {
                        assetAllData = assetAllData.concat(head.assetAll.rows);
                    }
                });

                //更新界面数据
                that.assetDataMap[currentPkaccbook] = assetAllData[0];
                //设置基本区域form的值
                that.basicInfoData = that.assetDataMap[currentPkaccbook];
                const basicInfoData4Form = that.getBasicInfoData4Form();
                // 设置财务区的值
                const accbookData4Form = that.getAccbookDataByPkaccbook4Form(currentPkaccbook);

                //财务区域未展开，展开财务区
                if (!that.state.financeShowFlag) {
                    that.setState({
                        financeShowFlag: true
                    });
                }

                let formValueObj = {};
                if (basicInfoData4Form) {
                    formValueObj[basicInfoForm] = basicInfoData4Form;
                }
                if (accbookData4Form && that.state.financeShowFlag) {
                    formValueObj[financeForm] = accbookData4Form;
                }
                that.props.form.setAllFormValue(formValueObj);

                if (successBack && isFunction(successBack)) {
                    successBack(assetAllData[0]);
                }
            } else {
                /*国际化处理：返回数据格式错误！*/
                showMessage(that.props, {content: getMultiLangByID('201201504A-000004'), color: 'danger'});
            }
        },
        error: (err) => {
            showMessage(that.props, {color: 'danger', content: err.message});
            if (errorBack && isFunction(errorBack)) {
                errorBack();
            }
        }
    });
}

/**
 * 加锁，解锁卡片
 */
function lockcards(lockflag, async = true) {
    let cuserid = getContext(loginContextKeys.userId, assetDataSource);
    let dataSourceOfServer = getContext(loginContextKeys.dataSourceCode, assetDataSource);

    let pk_card = this.getPkcardFromUrl();
    if (!pk_card) {
        return;
    }
    let allpks = [pk_card];
    let param = {
        allpks,
        msgMap: {
            usrid: cuserid,
            lockflag,
            dSource: dataSourceOfServer
        }
    };
    return lockrequest.call(this, param, async);
}

/**
 * 加解锁请求
 * @param {*} param
 * @param async
 */
function lockrequest(param, async = true) {
    let promise = new Promise(function (resolve, reject) {
        ajax({
            url: constants.URL.LockOrUnlockCard,
            data: param,
            async,
            success: (res) => {
                resolve();
            },
            error: (res) => {
                if (res && res.message) {
                    showMessage(null, {content: res.message, color: 'danger'});
                }
                reject();
            }
        });
    });

    return promise;
}

//联查设备卡片
function queryAboutCard(props) {
    const pk_equip = props.form.getFormItemsValue(basicInfoForm, 'pk_equip').value;
    if (pk_equip) {
        openEquipCardByPk(props, pk_equip);
    } else {
        /*国际化处理：选中的数据中第一条没有关联设备卡片！*/
        showMessage(props, {content: getMultiLangByID('201201504A-000020'), color: 'warning'});
    }
}

/**
 * 附件上传
 * @param  props
 */
function attachment(props) {
    //资产编码, 卡片主键
    let billId = props.form.getFormItemsValue(basicInfoForm, 'pk_card').value;
    props.ncUploader.show('uploader', {
        billId: 'fa/card/' + billId,
    });
}

//影像扫描
function faReceiptScan(props) {
    cardFaImageScan(props, getReceiptData(props));
}

//影像查看
function faReceiptShow(props) {
    cardFaImageView(props, getReceiptData(props));
}

//组装影像数据
function getReceiptData(props) {
    let pk_card = props.form.getFormItemsValue(basicInfoForm, 'pk_card').value;
    let billtype = props.form.getFormItemsValue(basicInfoForm, 'bill_type').value;
    let transi_type = props.form.getFormItemsValue(basicInfoForm, 'transi_type').value;
    let pk_org = props.form.getFormItemsValue(basicInfoForm, 'pk_org');
    let billmaketime = props.form.getFormItemsValue(basicInfoForm, 'billmaketime').value;
    let billmaker = props.form.getFormItemsValue(basicInfoForm, 'billmaker').value;
    let card_code = props.form.getFormItemsValue(basicInfoForm, 'card_code').value;

    return {
        pk_billid: pk_card,
        pk_billtype: billtype,
        pk_tradetype: transi_type,
        pk_org: pk_org.value,
        OrgNo: pk_org.value,
        pk_card: pk_card,
        BillType: transi_type,
        BillDate: billmaketime,
        Busi_Serial_No: pk_card,
        userid: billmaker,
        BillCode: card_code,
        OrgName: pk_org.display
    };
}

//单据追溯
function billreview() {
    //获取卡片来源
    const bill_source = this.props.form.getFormItemsValue(basicInfoForm, 'bill_source').value;
    //获取主键
    let pk = this.props.form.getFormItemsValue(basicInfoForm, 'pk_bill_src').value;

    //来源于盘盈单
    if (bill_source === BILL_SOURCE_TYPES.inventory_src) {
        pk = this.props.form.getFormItemsValue(basicInfoForm, 'pk_bill_src').value
            + '<:>' + this.props.form.getFormItemsValue(basicInfoForm, 'bill_code_src').value;
    }

    if (bill_source !== BILL_SOURCE_TYPES.handin_src) {
        if (pk) {
            CardLinkToBill.call(this, this.props, pk, bill_source);
        } else {
            /*国际化处理：该单据的来源单据号错误*/
            showMessage(this.props, {content: getMultiLangByID('201201504A-000021'), color: 'warning'});
        }
    } else {
        /*国际化处理：该单据没有来源单据*/
        showMessage(this.props, {content: getMultiLangByID('201201504A-000022'), color: 'warning'});
    }

}

//联查业务凭证
function faBillQueryAboutVoucher(that) {
    let linkCacheWord = '_LinkVouchar'; // 联查凭证标识

    let result = getCheckedAreaRow(that.props);

    if (result) {
        //选择的行数据
        let checkRow = result.rows[0].data;
        //选择的页签的主键字段
        let pkFiled = result.pkFiled;
        //选择的行数据主键
        let pk_bill = checkRow.values[pkFiled].value;
        //当前单据类型
        let bill_type = checkRow.values.bill_type.value;

        let pk_org = that.props.form.getFormItemsValue(constants.AREA.CARD.BASIC_INFO_AREA, 'pk_org').value;
        let pk_group = that.props.form.getFormItemsValue(constants.AREA.CARD.BASIC_INFO_AREA, 'pk_group').value;
        //let pk_accbook = props.form.getFormItemsValue(constants.AREA.CARD.BASIC_INFO_AREA,'pk_accbook').value;
        let pk_accbook = that.state.currentPkaccbook;

        let dataArray = getLinkData(pk_bill, bill_type, pk_org, pk_group, pk_accbook);

        // 命名格式为 appid_LinkVouchar,其中appid为自己小应用的应用编码
        let appId_LinkVouchar = that.props.pageConfig.appid + linkCacheWord;
        openToVouchar(that.props, appId_LinkVouchar, dataArray);
    }

}

function getLinkData(pk_bill, bill_type, pk_org, pk_group, pk_accbook) {
    let dataArray = [];

    let queryRelationIDUrl = constants.URL.QueryResourceid;

    //不需要特殊联查的单据
    let billtypeNoLink = [
        'HQ',//减值准备
        'HE' //评估单据
    ];

    let relationIDs = [];
    if (bill_type.indexOf('H') != 0 || billtypeNoLink.indexOf(bill_type) != -1) {
        relationIDs.push(pk_bill);
    } else {

        //变动单取前20位为主键
        if (bill_type.substring(0, 2) == 'HG') {
            pk_bill = pk_bill.substring(0, 20);
        }

        //其余单据走接口查询
        //接口参数
        let urlData = {
            bill_type: bill_type,
            pk_org: pk_org,
            pk_bill: pk_bill,
            pk_accbook: pk_accbook,
            pk_group: pk_group
        };
        ajax({
            url: queryRelationIDUrl,
            data: urlData,
            async: false,
            success: (res) => {
                if (res && res.data) {
                    relationIDs = res.data;
                }
            },
            error: (res) => {
                if (res && res.message) {
                    showMessage(null, {color: 'danger', content: res.message});
                }
            }
        });
    }

    for (let relationID of relationIDs) {
        let obj = {
            // pk_billtype 固定资产实际传入的是交易类型
            pk_billtype: null,
            relationID: relationID,
            pk_group: pk_group,
            pk_org: pk_org
        };
        dataArray.push(obj);
    }

    return dataArray;
}

//获取勾选的页签
function getCheckedAreaRow(props) {
    /** 表体行来源单据主键字段名 */
    const PK_BILL_Tab = "pk_bill";

    let result;
    //变动页签
    let rows = props.table.getCheckedRows(constants.AREA.CARD.ALTER_TAB);
    let pkFiled;
    if (rows && rows.length > 0) {
        pkFiled = PK_BILL_Tab;
        result = {
            rows,
            pkFiled
        };
        return result;
    }

    //评估页签
    rows = props.table.getCheckedRows(constants.AREA.CARD.EVALUATE_TAB);
    if (rows && rows.length > 0) {
        pkFiled = PK_BILL_Tab;
        result = {
            rows,
            pkFiled
        };
        return result;
    }

    //减值页签
    rows = props.table.getCheckedRows(constants.AREA.CARD.DEVALUE_TAB);
    if (rows && rows.length > 0) {
        pkFiled = PK_BILL_Tab;
        result = {
            rows,
            pkFiled
        };
        return result;
    }

    //减少页签
    rows = props.table.getCheckedRows(constants.AREA.CARD.REDUCE_TAB);
    if (rows && rows.length > 0) {
        pkFiled = PK_BILL_Tab;
        result = {
            rows,
            pkFiled
        };
        return result;
    }

    //调拨页签
    rows = props.table.getCheckedRows(constants.AREA.CARD.DEPLOY_TAB);
    if (rows && rows.length > 0) {
        pkFiled = PK_BILL_Tab;
        result = {
            rows,
            pkFiled
        };
        return result;
    }
    /*国际化处理：请选择页签中的一条记录*/
    showMessage(props, {content: getMultiLangByID('201201504A-000023'), color: 'danger'});
}


export {
    setStatus,
    linkToList,
    lockcards,
    lockrequest,
}



/*Hita0WssSbjpM+C19QDJ008vFiFXoRYM5fFc3Y8SmebGdTMFwKIbklXKmPe+JYpy*/